<?php
namespace app\weixin\controller;

//奖励物品
class Reward extends Base
{
	public function _initialize(){
		parent::_initialize();
	}

	public function index(){
		$map = [];
        $pagesize = config('paginate')['list_rows'];//每页数量
        $param=request()->param(); //获取url参数
        $lists = db('system_reward')->where($map)->order('id desc')->paginate($pagesize,false,array('query' => array_splice($param,1)));
        $arr = array();
        foreach ($lists as $value) {
        	$_t = $value;
        	if($value['target_type'] == 1) {
        		$find_box = db('box')->where(['id'=>$value['target_id']])->value('name');
        		$_t['name'] = $find_box;
        	} else {
        		$find_prop = db('prop')->where(['id'=>$value['target_id']])->value('name');
        		$_t['name'] = $find_prop;
        	}
        	$arr[] = $_t;
        }
        // dump($arr);
        $this->assign("lists",$arr);
        $this->assign("page", $lists->render());
        return $this->fetch();
	}

	//添加奖励物品
	public function add_reward(){
	    if(request()->ispost()){
			$data = input('post.');
			$data['create_time'] = time();
			$res = db('system_reward')->insertGetid($data);
			return $this->success('操作成功');
		}
		return $this->fetch();
	}

	//修改
	public function edit_reward(){
		$id = input('id');
		if (request()->isPost()) {
			$data = input('post.');
			$res = db('system_reward')->where(['id'=>$id])->update($data);
			return $this->success('操作成功');
		}
		$data = db('system_reward')->where(['id'=>$id])->find();
		if($data['target_type'] == 1 ) {
			$target_id = db('box')->where(['id'=>$data['target_id']])->find();
			$box = db('box')->field('id,name')->select();
			$this->assign('name',$box);
			
		} else {
			$target_id = db('prop')->where(['id'=>$data['target_id']])->find();
			$prop = db('prop')->field('id,name')->select();
			$this->assign('name',$prop);
		}
		// dump($target_id);
		// dump($data['target_type']);
		$this->assign('target_id',$target_id);
		$this->assign('data',$data);
		return $this->fetch('add_reward');
	}

	//异步请求
    public function onload(){
        $rid = input('rid');
        if($rid == 1) {
            $data = db('box')->select();
            echo json_encode($data);
        } else {
            $data = db('prop')->select();
            echo json_encode($data);
        }

    }


    //删除
    public function del_reward(){
    	$id = input('id');
    	$res = db('system_reward')->where(['id'=>$id])->delete();
    	return $this->success('操作成功');
    }
}


